<?php

namespace App\Http\Controllers;

use App\Product;
use App\ProductImg;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Buycar;
class ShopController extends Controller
{
    /**
     * @api getData
     * @method get
     * @comment 商品列表
     * @return mixed
     */
	public function getData()
	{
		$shops = Product::orderBy('id', 'asc')->get();
		return $shops;
	}
    
    /**
     * @api info
     * @method get
     * @comment 商品详情
     * @return mixed
     */
	public function info()
	{
		$id = $_GET['id'];
		$res = Product::findOrfail($id);
		$img = ProductImg::where(['product_id'=>$id])->get(['img']);
		$result['data'] = $res;
		$result['shopImg'] = $img;
		return $result;
	}
    
    /**
     * @api create
     * @method post
     * @comment 加入购物车
     * @param Request $request
     * @return false|string
     */
	public function create(Request $request)
	{
		$id = $request->id;
		$price = $request->price;
		$num = $request->num;
		$token = $request->token;
		$rows = DB::table('buycar')->where(['product_id' => $id])->get();
		$data = json_decode($rows, true);
		if (!$data == '') {
			return json_encode(['code' => 3, 'message' => '已添加，无需再次添加']);
		} else {
			$res = Buycar::create([
				'user_id' => $token,
				'product_id' => $id,
				'num' => $num,
				'unit_price' => $price,
			]);
			if ($res) {
				return json_encode(['code' => 1, 'message' => '添加成功']);
			} else {
				return json_encode(['code' => 0, 'message' => '添加失败']);
			}
		}
	}
}
